<template>
  <view class="container">
    <VForm
      ref="vform"
      :formOption="formOption"
      @onSubmit="onSubmit"
      :showButton="canEdit"
    >
      <template #beforehiddenLevel="{ form }">
        <uni-forms-item label="隐患名称" name="hiddenInventoryName" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="text" v-model="form.hiddenInventoryName" />
        </uni-forms-item>

        <uni-forms-item
          label="隐患来源"
          name="hiddenSource"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.hiddenSource"
            :localdata="hiddenSourceData"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item
          label="隐患分类"
          name="hiddenType"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.hiddenType"
            :localdata="hiddenTypeData"
          ></uni-data-select>
        </uni-forms-item>

        <!-- <uni-forms-item
          label="隐患等级"
          name="hiddenLevel"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.hiddenLevel"
            :localdata="hiddenLevelData"
          ></uni-data-select>
        </uni-forms-item> -->

        <uni-forms-item
          label="所属装置"
          name="deviceName"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.deviceName"
            :localdata="zzData"
            @change="fChangeDevice"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item
          label="所属部门"
          required
          name="deptName"
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <view style="display: flex">
            <uni-easyinput type="text" disabled v-model="form.deptName" :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]" />
            <button size="mini" @click.native="openTree(form)">选择</button>
          </view>
        </uni-forms-item>
        
        <uni-forms-item
          label="危害类型"
          name="harmType"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.harmType"
            :localdata="harmTypeData"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="治理资金" name="hiddenManagingFunds" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="text" v-model="form.hiddenManagingFunds" />
        </uni-forms-item>

        <uni-forms-item
          label="隐患治理类型"
          name="dangerManageType"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <uni-data-select
            v-model="form.dangerManageType"
            :localdata="dangerManageTypeData"
          ></uni-data-select>
        </uni-forms-item>


        <uni-forms-item label="隐患治理期限" name="rectificationEndTime" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-datetime-picker type="datetime" v-model="form.rectificationEndTime" />
        </uni-forms-item>

        <uni-forms-item label="隐患描述" name="hiddenInfo" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="textarea" v-model="form.hiddenInfo" />
        </uni-forms-item>

        <uni-forms-item label="形成原因" name="hiddenEntryBasis" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="textarea" v-model="form.hiddenEntryBasis" />
        </uni-forms-item>

        <uni-forms-item label="整改措施" name="hiddenRectificationMeasures" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="textarea" v-model="form.hiddenRectificationMeasures" />
        </uni-forms-item>

        <uni-forms-item label="隐患图片" name="files">
          <Camera v-model="files" :limit="5"> </Camera>
        </uni-forms-item>
        

        <uni-forms-item
          label="检查项"
          name="governCheckTaskItem"
          required
        >
          <uni-data-select
            v-model="form.governCheckTaskItem"
            v-if="!governCheckTaskItem"
            :localdata="checkTaskItemData"
            @change="fChangeCheckTaskItem"
          ></uni-data-select>

          <uni-easyinput v-else type="textarea" v-model="governCheckTaskItem" disabled :clearable="false" />
        </uni-forms-item>

        <uni-forms-item
          label="检查依据"
          name="governCheckBasis"
          required
          v-if="type != 'qyzzjc'">
          <uni-easyinput
            type="textarea"
            disabled :clearable="false"
            v-model="checkTaskData.governCheckBasis"
          ></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item
          label="检查方式"
          name="governCheckWay"
          required>
          <uni-easyinput
            type="text"
            disabled :clearable="false"
            v-model="checkTaskData.governCheckWay"
          ></uni-easyinput>
        </uni-forms-item>

        <view v-if="type != 'qyzzjc'">
          <uni-forms-item
            label="适用场合"
            name="governApplicablePlace"
            required>
            <uni-easyinput
              type="text"
              disabled :clearable="false"
              v-model="checkTaskData.governApplicablePlace"
            ></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item
            label="扣分"
            name="governDeductPoint"
            required>
            <!-- <uni-easyinput
              type="text"
              v-model="checkTaskScoreData.governDeductPoint"
            ></uni-easyinput> -->
            <uni-data-select
              v-model="checkTaskScoreData.governDeductPoint"
              @change="fChangeDeductPoint"
              :localdata="governDeductPointData">
            </uni-data-select>
          </uni-forms-item>

          <uni-forms-item
            label="否决项"
            name="governIsReject"
            required>
            <uni-data-select
              v-model="checkTaskScoreData.governIsReject"
              :localdata="governIsRejectData">
            </uni-data-select>
          </uni-forms-item>

          <uni-forms-item
            label="扣分说明"
            name="governDeductIllustrate"
            required>
            <uni-easyinput
              type="text"
              disabled :clearable="false"
              v-model="checkTaskScoreData.governDeductIllustrate"
            ></uni-easyinput>
          </uni-forms-item>
        </view>

        <uni-forms-item label="罚款金额" name="hiddenCheckPay" required :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]">
          <uni-easyinput type="text" v-model="form.hiddenCheckPay" />
        </uni-forms-item>
      </template>
      
      <template #last="{ form }">
        <uni-forms-item
          label="整改人"
          name="rectificationUserId"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <UserSelect
            :names="form.rectificationUserName"
            @change="onUserChange('rectificationUser', $event, form)"
            :limit="1"
          ></UserSelect>
        </uni-forms-item>
        <uni-forms-item
          label="复核人"
          name="reviewUserId"
          required
          :rules="[
            {
              required: true,
              errorMessage: '字段为必填项',
            },
          ]"
        >
          <UserSelect
            :names="form.reviewUserName"
            @change="onUserChange('reviewUser', $event, form)"
            :limit="1"
          ></UserSelect>
        </uni-forms-item>
      </template>
    </VForm>
    <view>
      <TreeDept
        v-show="showTree"
        :data="deptTree"
        :id="[]"
        :checkStrictly="true"
        @getChooseValue="getChooseDept"
        @close="closeTree"
      />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      row: {},
      type: '',
      isAdd: true
    };
  },
  onLoad(payload) {
    this.type = payload.type
    this.row = JSON.parse(decodeURIComponent(payload.row))
    this.isAdd = this.row.isAdd
    console.log('type: ', this.type)

    // if (payload.row) {
    //   this.isAdd = false;
    //   this.row = JSON.parse(decodeURIComponent(payload.row));
    // } else {
    //   this.isAdd = true;
    // }
  },
};
</script>

<script setup>
import { ref, getCurrentInstance, onMounted, watch } from "vue";
import VForm from "@/components/uniForm.vue";
import formJson from "./components/options.json";
import { useFormJson } from "@/hooks/jsonToForm.js";
import { apis as APIS } from "@/api/yhpc/yhdj.js";
// import { useInputData } from "@/hooks/useInputData.js";
import { listUser } from "@/api/user.js";
import Camera from "@/components/camera.vue";
import { router } from "@/router/index.js";
import UserSelect from "@/components/user-select.vue";
import { getDeptTree } from "@/api/common.js";
import TreeDept from "@/components/treeSelect/index.vue";
import { useAuthStore } from "@/store/modules/auth.js";
import { parseTime } from "@/utils/index.js";

const authStore = useAuthStore();
const done = () => {
  router.back();
};

const formOption = ref(
  useFormJson(formJson, {
    sort: [],
    sortable: [],
  })
);
const onUserChange = (key, e, data) => {
  if (e.list.length > 0) {
    form.value[key + "Id"] = e.ids;
    form.value[key + "Name"] = e.names;
    data[key + "Id"] = e.ids;
    data[key + "Name"] = e.names;
    e.done(form.value[key + "Name"]);
  } else {
    e.done("");
  }
};

const sonTypes = ref([]);

// 文件
const files = ref([]);
// watch(
//   () => files,
//   (newData) => {
//     form.value.hiddenFileId = newData.value
//       .map((item) => (item ? item.id : ""))
//       .join(",");
//   },
//   {
//     deep: true,
//   }
// );

const vform = ref();
const canEdit = ref(true);
const rowData = ref({})
const checkTaskData = ref({});
const checkTaskItemData = ref([])
const governCheckTaskItem = ref()
const checkTaskScoreData = ref({
  governDeductPoint: null, 
  governIsReject: '',
  governDeductIllustrate: ''
})
const form = ref({
  hiddenBelongType: 0  // 隐患类别 默认 0:其他隐患
})
const detailData = ref({})

onMounted(() => {
  const { row, isAdd } = getCurrentInstance().data;
  rowData.value = row

  // 检查项
  governCheckTaskItem.value = row.governCheckName+row.governCheckContent
  checkTaskData.value.governCheckBasis = row.governCheckBasis
  checkTaskData.value.governCheckWay = row.governCheckWay
  checkTaskData.value.governApplicablePlace = row.governApplicablePlace

  // 查分数
  if(row.governCheckTaskItemId){
    fGetCheckTaskItemScore(row.governCheckTaskItemId)
  }

  getDeptTree().then((res) => {
    deptTree.value = res.data;
  });

  
  // 隐患详情
  console.log(row.hiddenInventoryId, ' =====hiddenInventoryId')
  if(row.hiddenInventoryId){
    fGetHiddenDetail(row.hiddenInventoryId)
  }else{
    // 检查项
    console.log('检查项222====非详情')
    fGetCheckTaskItemList()
  }

  if (isAdd) {
    vform.value.setFormData({
      hiddenCheckUser: authStore.user.nickName,
      hiddenCheckTime: parseTime(new Date()),
    });
    canEdit.value = true;
    return;
  } else {
    canEdit.value = false;
    // files.value = row.fileManageList;
    // if (
    //   row.hiddenProgress != "待审核" &&
    //   row.hiddenProgress != "待修改" &&
    //   row.hiddenProgress != "已驳回"
    // ) {
    //   canEdit.value = false;
    // } else {
    //   canEdit.value = true;
    // }
    // vform.value.setFormData(row);
  }
  
});

// 隐患详情
const fGetHiddenDetail = (hiddenInventoryId) => {
  APIS.getHiddenDetail(hiddenInventoryId).then(res => {
    detailData.value = res.data
    
    // let deviceName = {
    //   value: {deviceName: res.data.deviceName, deptId: 25},
    //   text: res.data.deviceName,
    // }
    // let data = {
    //   ...res.data,
    //   deviceName: deviceName
    // }

    vform.value.setFormData(res.data);

    if(rowData.value.hiddenInventoryId){
      console.log('检查项111====')
      fGetCheckTaskItemList(res.data.governCheckTaskId, res.data.governCheckTaskItemId)
    }
  })
}

// 组织树 责任人 相关逻辑
const deptTree = ref([]);

const showTree = ref(false);
const closeTree = () => {
  showTree.value = false;
};
const deptForm = ref({});
const openTree = (form) => {
  deptForm.value = form;
  showTree.value = true;
};
const getChooseDept = (ids, item) => {
  deptForm.value.deptName = item[item.length - 1].label;
  deptForm.value.deptId = item[item.length - 1].id;
};

const onSubmit = (data) => {
  const plugForm = {
    ...form.value,
    hiddenCheckType: '企业自查',  // 排查类型
    checkLevel: '公司级'  // 排查级别
  }
  if (data.id) {
    APIS.update({ ...data, ...plugForm }).then((res) => {
      uni.showToast({
        title: "修改成功",
        icon: "succes",
      })
      setTimeout(() => {
        done && done()
      }, 2000);
    })
  } else {
    APIS.governHiddenInventoryAdd({ ...data, ...plugForm, ...rowData.value }).then((res) => {
      uni.showToast({
        title: "新增成功",
        icon: "succes",
      })

      console.log(rowData.value, ' rowData.value')
      // 从任务项点击不符合进来的，录入隐患完成后调用状态接口，更新状态
      if(rowData.value.governTaskPlanItemId){
        let data = {
          governTaskPlanItemId: rowData.value.governTaskPlanItemId,
          governCheckConform: 1  // 0符合 1不符合 2待定中  默认null
        }
        APIS.fixCheckTaskItemStatus(data).then(res => {})
      }

      setTimeout(() => {
        done && done()
      }, 2000);
    })
  }
}

// 所属装置
const zzData = ref([]);
APIS.zz().then((res) => {
  zzData.value = res.rows.map((item) => ({
    value: item,
    text: item.deviceName,
  }));
});

const fChangeDevice = (e) => {
	console.log(e);
  form.value.deviceId = e.id
  form.value.deviceName = e.deviceName
}

// 隐患来源
const hiddenSourceData = ref([]);
APIS.getHiddenSource().then((res) => {
  hiddenSourceData.value = res.data.map((item) => ({
    value: item,
    text: item
  }));
});

// 隐患类型
const hiddenTypeData = ref([]);
APIS.getHiddenType().then((res) => {
  hiddenTypeData.value = res.data.map((item) => ({
    value: item,
    text: item
  }));
});

// 隐患等级
const hiddenLevelData = ref([
  { value: "一般隐患", text: "一般隐患" },
  { value: "重大隐患", text: "重大隐患" }
])

// 危害类型
const harmTypeData = ref([
  { value: "事故隐患", text: "事故隐患" },
  { value: "火灾隐患", text: "火灾隐患" }
])

// 隐患治理类型
const dangerManageTypeData = ref([
  { value: "即查即改", text: "即查即改" },
  { value: "限期整改", text: "限期整改" }
])

// 否决项
const governIsRejectData = ref([
  { value: "1", text: "是" },
  { value: "0", text: "否" }
])

// 检查项
const fGetCheckTaskItemList = (governCheckTaskId, governCheckTaskItemId) => {
  let _id = governCheckTaskId ? governCheckTaskId : rowData.value.governCheckTaskId
  APIS.getCheckTaskItemList({ governCheckTaskId: _id }).then(res => {
    checkTaskItemData.value = res.rows.map((item) => ({
      value: item,
      text: `${item.governCheckName}${item.governCheckContent}`
    }));

    console.log(governCheckTaskId, ' governCheckTaskId')
    if(governCheckTaskId){
      res.rows.map(item => {

        // console.log(item.governCheckTaskId, ' item.governCheckTaskItemId')

        if(item.governCheckTaskItemId == governCheckTaskItemId){

          console.log('123123:===', item.governCheckTaskItemId == governCheckTaskItemId)

          
          form.value.governCheckTaskItem = item
          vform.value.setFormData({
            ...detailData.value,
            governCheckTaskItem: item
          });

          console.log('item', item)
          
          checkTaskData.value.governCheckBasis = item.governCheckBasis
          checkTaskData.value.governCheckWay = item.governCheckWay
          checkTaskData.value.governApplicablePlace = item.governApplicablePlace

          // 扣分规则
          fGetCheckTaskItemScore(item.governCheckTaskItemId, item.governCheckTaskItemScoreId)
        }
      })
    }
  })
};

// 查询【检查项】扣分规则
const governDeductPointData = ref([])
const fGetCheckTaskItemScore = (e, governCheckTaskItemScoreId) => {
  APIS.getCheckTaskItemScore(e).then(res => {
    // checkTaskScoreData.value = res.data

    governDeductPointData.value = res.data.map((item) => ({
      value: item,
      text: item.governDeductPoint
    }));

    // 编辑进来回显扣分规则
    console.log('00000===',  governCheckTaskItemScoreId)
    if(governCheckTaskItemScoreId){
      res.data.map(item => {
        console.log('123123===',  item.governCheckTaskItemScoreId)
        console.log('99999===',  governCheckTaskItemScoreId)


        if(item.governCheckTaskItemScoreId == governCheckTaskItemScoreId){
          form.value.governCheckTaskItemId = item.governCheckTaskItemId
          form.value.governCheckTaskItemScoreId = item.governCheckTaskItemScoreId

          console.log('governCheckTaskItemId',  item.governCheckTaskItemId)
          vform.value.setFormData({
            ...detailData.value,
            governCheckTaskItemId: item.governCheckTaskItemId,
            governCheckTaskItemScoreId: item.governCheckTaskItemScoreId
          });
        }
      })
    }

    console.log('checkTaskScoreData.value', checkTaskScoreData.value)
    // checkTaskScoreData.value.governIsReject = checkTaskScoreData.value.governIsReject === 1 ? '是' : '否'
  })
};

// 选择扣分，带出扣分说明、否决项
const fChangeDeductPoint = (e) => {
  checkTaskScoreData.value = e
  form.value.governCheckTaskItemId = e.governCheckTaskItemId
  form.value.governCheckTaskItemScoreId = e.governCheckTaskItemScoreId
}

// 选择检查项带出扣分规则
const fChangeCheckTaskItem = (item) => {
  console.log('item', item)
  if(item){
    checkTaskData.value = item
    fGetCheckTaskItemScore(item.governCheckTaskItemId)
  }else{
    checkTaskData.value = {}
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  padding: 24upx;
}

:deep .uni-select__input-box{
  overflow: hidden;
}
</style>
